package twentytwenty;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: Spider Man
 * @Description: 13.罗马数字转为阿拉伯数字
 * @Date Created in 2020-09-21 9:08
 * @Modified By:
 */
public class RomanToInt_13 {
    public static void main(String[] args) {
        String s = "MCMXCIV";
        System.out.println(romanToInt(s));
    }

    public static int romanToInt(String s) {
        Map<String,Integer> map = new HashMap<>();
        map.put("I",1);
        map.put("V",5);
        map.put("X",10);
        map.put("L",50);
        map.put("C",100);
        map.put("D",500);
        map.put("M",1000);
        map.put("IV",4);
        map.put("IX",9);
        map.put("XL",40);
        map.put("XC",90);
        map.put("CD",400);
        map.put("CM",900);

        int length = s.length();
        int result = 0;
        int i = 0;
        while (i < length){
            if (i < length-1 && map.containsKey(s.substring(i,i + 2))){
                result += map.get(s.substring(i,i + 2));
                i += 2;
            }else if (map.containsKey(s.substring(i,i + 1))){
                result += map.get(s.substring(i,i + 1));
                i ++;
            }
        }
        return result;
    }
}
